package com.example.android.http

import com.example.android.http.error.ApiException
import com.example.android.http.error.ExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart

/**
 * @author zjc
 * @date 2023/11/1
 */

suspend fun <T> requestFlow(
    api: suspend () -> BaseResponse<T>,
    onStart: (() -> Unit)? = null,
    onComplete: (() -> Unit)? = null,
    onFail: ((code: Int, msg: String) -> Unit)? = null
): Flow<T> = flow {
    val response = api()
    if (response.errorCode == 0) {
        emit(response.data)
    } else {
        throw ApiException(response.errorCode, response.errorMsg)
    }
}.flowOn(Dispatchers.IO)
    .onStart {
        onStart?.invoke()
    }
    .catch {
        val exception = ExceptionHandler.handleException(it)
        onFail?.invoke(exception.errCode, exception.errMsg)
    }
    .onCompletion {
        onComplete?.invoke()
    }
